package com.house365.im.client.util;

import java.io.File;
import java.io.RandomAccessFile;

import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.text.TextUtils;

/**
 *@Author Rick.Ping
 *@Date 2014-8-15
 *@Comment
 **/
public class MediaUtil {
	private static MediaUtil instance = null;
	private MediaPlayer mp;
	private OnCompletionListener old;
	private String mPath;
	
	private MediaUtil(){
		 mp= new MediaPlayer();
	}
	public static MediaUtil getInstance(){
		if(instance == null){
			instance = new MediaUtil();
		}
		return instance;
	}
	
	public long getDuration(String path){
		File file = new File(path);
		long duration = -1;
		int[] packedSize = { 12, 13, 15, 17, 19, 20, 26, 31, 5, 0, 0, 0, 0, 0,
				0, 0 };
		RandomAccessFile randomAccessFile = null;
		try {
		    randomAccessFile = new RandomAccessFile(file, "rw");
			long length = file.length();// 文件的长度
			int pos = 6;// 设置初始位置
			int frameCount = 0;// 初始帧数
			int packedPos = -1;
			byte[] datas = new byte[1];// 初始数据值
			while (pos <= length) {
				randomAccessFile.seek(pos);
				if (randomAccessFile.read(datas, 0, 1) != 1) {
					duration = length > 0 ? ((length - 6) / 650) : 0;
					break;
				}
				packedPos = (datas[0] >> 3) & 0x0F;
				pos += packedSize[packedPos] + 1;
				frameCount++;
			}
			duration += frameCount * 20;// 帧数*20
			
			if (randomAccessFile != null) {
				randomAccessFile.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return duration;
	}
  
	public void playVoice(String path,OnCompletionListener listener) {
		try {
			if (mp.isPlaying()) {
				//将老的老的暂停
				if(old!= null){
					old.onCompletion(mp);
				}
				mp.stop();
				if (!TextUtils.isEmpty(mPath) && mPath.equals(path)) {
					//播放的是同一个文件， 停止播放
					return;
				}
			}
			
			mPath = path;
			mp.reset();
			mp.setDataSource(path);
			mp.prepare();
			mp.start();
			old= listener;
			mp.setOnCompletionListener(listener);
			
		} catch (Exception e) {
			e.printStackTrace();
			if(listener!= null){
				listener.onCompletion(mp);
			}
		}

	}
	
	public void stopPlay() {
		if (mp.isPlaying()) {
			if(old!= null){
				old.onCompletion(mp);
			}
			mp.stop();
		}
	}
}
